package com.jbt.mds.obdsdk

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.jbt.mds.obdsdk.databinding.ActivityDeviceInfoBinding
import com.jbt.mds.sdk.bluetooth.BluetoothEvent
import com.jbt.mds.sdk.diagnosis.dtc.Dtc
import com.jbt.mds.sdk.model.DataStreamInfo
import com.jbt.mds.sdk.obd.AbortCode
import com.jbt.mds.sdk.obd.IObdDetector
import com.jbt.mds.sdk.obd.ObdDetector
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class DeviceInfoActivity : AppCompatActivity(), IObdDetector, PermissionInterface {
    lateinit var mObdDetector: ObdDetector
    private val TAG = "ObdDetector"
    lateinit var binding:ActivityDeviceInfoBinding


    override fun getPermissionsRequestCode(): Int {
        return 10000
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    override fun getPermissions(): Array<String>? {
        return arrayOf<String>(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }

    override fun requestPermissionsSuccess() {
        Log.i(TAG, "requestPermissionsSuccess:  授权成功， 可以正常使用")
    }

    override fun requestPermissionsFail() {
        Log.i(TAG, "requestPermissionsFail: 授权失败！请把定位、存储等权限授权给应用， 否则无法使用")
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDeviceInfoBinding.inflate(layoutInflater)
        setContentView(binding.root)

        mObdDetector = ObdDetector.getInstance()
        mObdDetector.init(this, this)


        if (TextUtils.isEmpty(mObdDetector.obdSdkVciSn)) {
            binding.etVciSn.setText("602203000404")
            binding.etVciAddr.setText("8CDE52DE6A45")
            binding.etVciPin.setText("6912")
        } else {
            binding.etVciSn.setText(mObdDetector.obdSdkVciSn)
            binding.etVciAddr.setText(mObdDetector.obdSdkVciAddr)
            binding.etVciPin.setText(mObdDetector.obdSdkVciPin)
        }

        binding.back.setOnClickListener {
//            finish()
            val intent = Intent(this, MainActivity2::class.java)
            startActivity(intent) // 启动 SecondActivity
        }
        binding.connectVci.setOnClickListener {
            println("123123123")
            println(binding.etVciSn.getText().toString()+"3333333333333333333")
            mObdDetector.commInit(
                binding.etVciSn.getText().toString(),  binding.etVciAddr.getText().toString(),
                binding.etVciPin.getText().toString(), true, true
            )
            mObdDetector.saveObdSdkVciSn( binding.etVciSn.getText().toString())
            mObdDetector.saveObdSdkVciAddr( binding.etVciAddr.getText().toString())
            mObdDetector.saveObdSdkVciPin( binding.etVciPin.getText().toString())
            print(binding.etVciPin.getText().toString()+123)

            binding.txtsbh.text = "已绑定设备号:${binding.etVciSn.getText()}"
            Log.i(TAG,"onclick")
            Log.i(TAG,"onclick")

        }

        mPermissionHelper = PermissionHelper(this, this)
        mPermissionHelper?.requestPermissions()


        EventBus.getDefault().register(this)
    }
    protected var mPermissionHelper: PermissionHelper? = null

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(msg: Message) {

        Log.i(TAG,"onEvent  ${msg}")


        when (msg.what) {
            BluetoothEvent.CONNECT_OUT_TIME -> {
                Log.i(
                    TAG,
                    "BluetoothEvent.CONNECT_OUT_TIME :" + BluetoothEvent.CONNECT_OUT_TIME
                )
            }
            BluetoothEvent.CONNECT_SUCCESS -> {
                Log.i(
                    TAG,
                    "BluetoothEvent.CONNECT_SUCCESS :" + BluetoothEvent.CONNECT_SUCCESS
                )
            }
            BluetoothEvent.CONNECT_FAILED -> {
                Log.i(
                    TAG,
                    "BluetoothEvent.CONNECT_FAILED :" + BluetoothEvent.CONNECT_FAILED
                )
            }
            BluetoothEvent.VCI_ILLEGAL -> {
                Log.i(
                    TAG,
                    "BluetoothEvent.VCI_ILLEGAL :" + BluetoothEvent.VCI_ILLEGAL
                )
            }
            BluetoothEvent.DISCONNECT -> {
                Log.i(
                    TAG,
                    "BluetoothEvent.DISCONNECT :" + BluetoothEvent.DISCONNECT
                )
            }
            BluetoothEvent.DISCONNECT_CONFIRM -> {
                Log.i(
                    TAG,
                    "BluetoothEvent.START_CONNECT :" + BluetoothEvent.START_CONNECT
                )
            }
            BluetoothEvent.START_CONNECT -> {
            }
        }
    } 


    override fun activeSuccess() {
    }

    override fun abortError(abortCode: AbortCode) {
        Log.i(TAG, "abortError abortCode:$abortCode")

        Toast.makeText(this, "检测出错，错误代码：$abortCode", Toast.LENGTH_SHORT).show()
    }

    override fun stopFinish() {
    }

    override fun updateDataStream(p0: DataStreamInfo?) {
    }

    override fun updateRealDtc(p0: MutableList<Dtc>?) {
    }

    override fun updateRealFreezeFrameDataStream(p0: MutableList<DataStreamInfo>?) {
    }

    /**
     * VCI连接状态变化时发生回调
     *
     * @param vciConnectState
     */
    override fun updateVciConnectedState(vciConnectState: Int) {

        Log.i(
            TAG,
            "updateVciConnectedState: vciConnectState：$vciConnectState"
        )
        Toast.makeText(this@DeviceInfoActivity, "蓝牙连接状态：$vciConnectState", Toast.LENGTH_SHORT)
            .show()

        val intent = Intent(this, MainActivity2::class.java)
        startActivity(intent)
    }

    override fun scanProgress(p0: String?, p1: Int) {
    }
} 